package logic

import (
	"context"
	"errors"
	"shop/models"
	"shop/pkg"

	"shop/shopRpc/internal/svc"
	"shop/shopRpc/shopRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *shopRpc.OrderAddRequest) (*shopRpc.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	orderSn := pkg.OrderGen() //生成订单号

	total := 0.0
	var orderItems []models.OrdersItem
	for _, item := range in.Items {
		var goods models.Goods
		err := models.DB.Where("id = ?", item.GoodsId).First(&goods).Error
		if err != nil {
			return nil, errors.New("商品不存在")
		}
		subTotal := goods.Price * float64(item.Quantity) //小记
		total += subTotal

		orderItem := models.OrdersItem{
			GoodsID:    int64(goods.ID),
			GoodsName:  goods.Name,
			GoodsPrice: goods.Price,
			GoodsImg:   goods.Img,
			Quantity:   item.Quantity,
			Subtotal:   subTotal,
		}
		orderItems = append(orderItems, orderItem)
	}
	order := models.Order{
		UserID:    in.UserId,
		OrderSn:   orderSn,
		Total:     total,
		AddressID: in.AddressId,
		Status:    1,
		PayType:   int(in.PayType),
	}

	err := models.DB.Create(&order).Error
	if err != nil {
		return nil, errors.New("订单创建失败")
	}

	for i, _ := range orderItems {
		orderItems[i].OrderID = int64(order.ID)
	}

	//
	err = models.DB.Create(&orderItems).Error
	if err != nil {
		return nil, errors.New("订单明细创建失败")
	}

	return &shopRpc.OrderAddResponse{
		OrderSn: orderSn,
		Total:   float32(total),
	}, nil
}
